﻿using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WcsZz.Extend;
using wms_wpf.Apiservice;
using wms_wpf.Dto;
using wms_wpf.InPut;
using wms_wpf.Views;

namespace wms_wpf.ViewModels.ExpressChildViewModel
{
     public partial class MaterialChildViewModel : BindableBase, INavigationAware
    {

        private readonly MaterialView materialView;
        private readonly IEssService essService;
        string Machine = Environment.GetEnvironmentVariable("Machine", EnvironmentVariableTarget.Machine);
        public MaterialChildViewModel()
        {
            this.materialView = new MaterialView();
            View_MaterialsDtos = new List<View_MaterialsDto>();
            InPut_ViewService = new InPut_ViewService();
            InPut_BaseService10 = new InPut_BaseService10();
            InPut_BaseService7 = new InPut_BaseService7();
            Inlethousecodes = new List<string>();
            InlethousecodesIn = new List<string>();
            CustomInPut4 = new CustomInPut4();
            InPut_BaseService12 = new InPut_BaseService12();
            InPut_ViewService.PageIndex = 1;
            InPut_ViewService.PageSize = 20;
            GetList_View_MaterialsCommand = new DelegateCommand(GetList_View_Materials);
            CreateNeetOutMaterialCommand = new DelegateCommand(CreateNeetOutMaterial);
            CreateMaterialBaseCommand = new DelegateCommand(CreateMaterialBase);
            CreateTaskOrderCommand = new DelegateCommand(CreateTaskOrder);
            DeleteMaterialCommand = new DelegateCommand(DeleteMaterial);
            service = new ViewService();
            baseService = new BaseService();
            essService = new EssService();
            customService = new CustomService();
            GetList_View_Materials();
            GetList_InlethouesCode();
            GetList_InlethouesCodeInPut();
            EventAggregatorHelper.EventAggregator.ResgiterMessage(async arg =>
            {

                GetList_View_Box_Material();


            }, "GetList_View_Box_Material");
            if (Machine == "2")
            {
                ComboxMachine = 1;
            }
            else
            {
                ComboxMachine = 0;
            }
        }


        private List<View_MaterialsDto> view_MaterialsDtos;
        public List<View_MaterialsDto> View_MaterialsDtos
        {
            get { return view_MaterialsDtos; }
            set { view_MaterialsDtos = value; RaisePropertyChanged(); }
        }
        public DelegateCommand GetList_View_MaterialsCommand { get; set; }
        public DelegateCommand CreateNeetOutMaterialCommand { get; set; }
        public DelegateCommand CreateMaterialBaseCommand { get; set; }
        public DelegateCommand CreateTaskOrderCommand { get; set; }
        public DelegateCommand DeleteMaterialCommand { get; set; }
        private InPut_ViewService inPut_ViewService;
        public InPut_ViewService InPut_ViewService
        {
            get { return inPut_ViewService; }
            set { inPut_ViewService = value; RaisePropertyChanged(); }
        }
        private InPut_BaseService10 inPut_BaseService10;
        public InPut_BaseService10 InPut_BaseService10
        {
            get { return inPut_BaseService10; }
            set { inPut_BaseService10 = value; RaisePropertyChanged(); }
        }
        private InPut_BaseService7 inPut_BaseService7;
        public InPut_BaseService7 InPut_BaseService7
        {
            get { return inPut_BaseService7; }
            set { inPut_BaseService7 = value; RaisePropertyChanged(); }
        }
        private InPut_BaseService12 inPut_BaseService12;
        public InPut_BaseService12 InPut_BaseService12
        {
            get { return inPut_BaseService12; }
            set { inPut_BaseService12 = value; RaisePropertyChanged(); }
        }
        private string fullCode;
        public string FullCode
        {
            get { return fullCode; }
            set { fullCode = value; RaisePropertyChanged(); }
        }
        private string lpn;
        public string LPN
        {
            get { return lpn; }
            set { lpn = value; RaisePropertyChanged(); }
        }

        private int comboxMachine;
        public int ComboxMachine
        {
            get { return comboxMachine; }
            set { comboxMachine = value; RaisePropertyChanged(); }
        }

        [RelayCommand]
        private void test(string parameter)
        {
            MessageBox.Show(parameter);
        }


        private List<View_Box_MaterialDto> view_Box_MaterialDtos;
        public List<View_Box_MaterialDto> View_Box_MaterialDtos
        {
            get { return view_Box_MaterialDtos; }
            set { view_Box_MaterialDtos = value; RaisePropertyChanged(); }
        }
        public CustomInPut4 CustomInPut4;
        private long count;
        public long Count
        {
            get { return count; }
            set { count = value; RaisePropertyChanged(); }
        }
        private long pagecount;
        public long PageCount
        {
            get { return pagecount; }
            set { pagecount = value; RaisePropertyChanged(); }
        }
        public IViewService service { get; set; }
        public IBaseService baseService { get; set; }
        public ICustomService customService { get; set; }
        private List<string> inlethousecodes;
        public List<string> Inlethousecodes
        {
            get { return inlethousecodes; }
            set { inlethousecodes = value; RaisePropertyChanged(); }
        }
        private List<string> inlethousecodesIn;
        public List<string> InlethousecodesIn
        {
            get { return inlethousecodesIn; }
            set { inlethousecodesIn = value; RaisePropertyChanged(); }
        }
        private async void GetList_View_Materials()
        {

            try
            {


                Tuple<List<View_MaterialsDto>, long?, long?> tuple = await service.GetList_View_Materials(InPut_ViewService);
                if (tuple == null)
                {
                    return;
                }
                View_MaterialsDtos = tuple.Item1;
                Count = (long)tuple.Item2;
                PageCount = (long)tuple.Item3;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LognetHelper.WriteLog("系统-GetList_View_Materials", ex);
            }

        }
        private async void CreateNeetOutMaterial()
        {
            try
            {
                if (materialView.datagrid.SelectedItems.Count == 0)
                {
                    return;
                }
                foreach (View_MaterialsDto item in materialView.datagrid.SelectedItems)
                {
                    InPut_BaseService10.MaterialCodes.Add(item.MaterialCode);
                }
                if (string.IsNullOrEmpty(InPut_BaseService10.InlethouseCode)) { Growl.Info("请选择出库口", "msg"); return; }
                if (Machine == "3")
                {
                    InPut_BaseService10.InlethouseCode = "3";
                }
                bool Nullres = InPut_BaseService10.GetType().GetProperties().All(property => !string.IsNullOrEmpty(property.GetValue(InPut_BaseService10).ToString()));
                if (!Nullres)
                {
                    Growl.Info("请填写完整", "msg"); return;
                }
                await baseService.CreateNeetOutMaterial(InPut_BaseService10);
                InPut_BaseService10.MaterialCodes.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LognetHelper.WriteLog("系统-CreateNeetOutMaterial", ex);
            }

        }
        private async void GetList_InlethouesCode()
        {
            try
            {
                Inlethousecodes = await baseService.GetList_InlethouesCode("出口");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LognetHelper.WriteLog("系统-GetList_InlethouesCode", ex);
            }

        }
        private async void GetList_InlethouesCodeInPut()
        {
            try
            {
                InlethousecodesIn = await baseService.GetList_InlethouesCode("入口");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LognetHelper.WriteLog("系统-GetList_InlethouesCode", ex);
            }
        }
        private async void CreateMaterialBase()
        {
            try
            {
                string BoxCode = await essService.queryNodeReader();
                if (!string.IsNullOrEmpty(BoxCode))
                {
                    InPut_BaseService7.BoxGridCode = BoxCode;
                }


                materialView.textbox.Focus();
                if (!string.IsNullOrEmpty(materialView.textbox.Text))
                {
                    materialView.fullcodetextbox.Focus();
                }

                if (string.IsNullOrEmpty(InPut_BaseService7.BoxGridCode)) { Growl.Info("箱号必须填写", "msg"); return; }
                if (string.IsNullOrEmpty(FullCode)) { Growl.Info("请填写二维码", "msg"); return; }
                CustomInPut customInPut = new CustomInPut();
                // 使用 Split 方法，传入分隔符
                string[] parts = FullCode.Split('&');
                customInPut.reelId = parts[0];
                customInPut.fullCode = FullCode;
                //mes判定
                int res = await customService.instoreess(customInPut);
                if (res != 0) return;
                if (parts.Length < 4)
                    return;
                InPut_BaseService7.MaterialCode = parts[0];
                InPut_BaseService7.MaterialName = parts[1];
                InPut_BaseService7.Batch = parts[2];
                InPut_BaseService7.Quantity = parts[5];
                materialView.fullcodetextbox.Focus();
                //通知mes
                CustomInPut2 customInPut2 = new CustomInPut2();
                customInPut2.reelId = parts[0];
                customInPut2.location = InPut_BaseService7.BoxGridCode.Substring(0, 10);
                customInPut2.fullCode = FullCode;
                customInPut2.source = "ESS";
                customInPut2.type = 0;
                customInPut2.w = 7;
                customInPut2.h = 8;
                string msg = await customService.instorefinishess(customInPut2);
                if (msg != "ok") return;
                //mes没问题记录日志 更新物料          
                bool res2 = await baseService.CreateMaterialBase(InPut_BaseService7);
                if (res2)
                {
                    //Reel reel = new Reel();
                    //reel.ReelId = InPut_BaseService7.MaterialCode;
                    //CustomInPut4.data.Add(reel);
                    await baseService.CreateLog("入料", parts[0] + "加入料盒" + "," + InPut_BaseService7.MaterialName + InPut_BaseService7.BoxGridCode);
                    //MessageBox.Show(CustomInPut4.data.ToString());
                }
                FullCode = "";
                GetList_View_Box_Material();


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LognetHelper.WriteLog("系统-CreateMaterialBase", ex);
            }
        }
        public async void GetList_View_Box_Material()
        {
            try
            {
                if (!string.IsNullOrEmpty(materialView.textbox.Text))
                {
                    InPut_BaseService7.BoxGridCode = materialView.textbox.Text;
                }
                if (string.IsNullOrEmpty(InPut_BaseService7.BoxGridCode)) return;
                View_Box_MaterialDtos = await service.GetList_View_Box_Material(InPut_BaseService7.BoxGridCode);
                materialView.quantity.Text = View_Box_MaterialDtos.Count().ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LognetHelper.WriteLog("系统-GetList_InlethouesCode", ex);
            }

        }
        private async void CreateTaskOrder()//添加入库任务
        {
            //CustomInPut4.rackcode = "HAI-001-004-003";
            //await customService.NotifyMes(CustomInPut4);

            try
            {
                string boxcode = await essService.queryNodeReader();
         
                    if (string.IsNullOrEmpty(boxcode))
                    {
                        Growl.Info("拣选位无料盒,无法上架", "msg"); return;
                    }
                    else
                    {
                        InPut_BaseService12.BoxCode = boxcode;
                    }

                if (string.IsNullOrEmpty(InPut_BaseService12.BoxCode)) { Growl.Info("箱号必须填写", "msg"); return; }
                InPut_BaseService12.BoxCode = InPut_BaseService7.BoxGridCode.Substring(0, 10);
           
                if (string.IsNullOrEmpty(InPut_BaseService12.InlethouseCode)) { Growl.Info("请选择入库口", "msg"); return; }

                //生成任务
                if (Machine == "3")
                {
                    InPut_BaseService12.InlethouseCode = "LT_CONVEYOR_OUTPUT:POINT:68949:16575";
                }
                string taskorderCode = await baseService.CreateTaskOrder(InPut_BaseService12);
                if (taskorderCode == null) return;
                View_TaskOrderDto dto = await service.SingleView_TaskOrder(taskorderCode);
              
                    if (boxcode != dto.BoxCode)
                    {
                        Growl.Info("料盒码不一致,无法上架", "msg"); return;
                    }
                
                //发送任务给agv
                Ess_Input ess_Input = new Ess_Input();
                ess_Input.taskType = "putaway";
                ess_Input.taskGroupCode = "taskGroupCode-001";
                ess_Input.groupPriority = 0;
                List<Tasks> data = new List<Tasks>();
                Tasks ta = new Tasks();
                ta.taskCode = dto.TaskOrderCode;
                ta.taskPriority = 0;
                data.Add(ta);
                ess_Input.tasks = data;
                TaskDescribe td = new TaskDescribe();
                td.containerCode = dto.BoxCode;
                td.containerType = "CT_KUBOT_STANDARD";
                td.storageTag = "";
                td.fromLocationCode = dto.InlethouseCode;
                td.toLocationCode = dto.WarehouseCode;
                td.toStationCode = "haiport_station_1";
                td.isPutaway = false;
                ta.taskDescribe = td;
                string res = await essService.CreateTask(ess_Input);
                if (res.Contains("OK"))
                {

                    await essService.moveContainer(dto.BoxCode);
                    InPut_BaseService11 inPut = new InPut_BaseService11();
                    inPut.TaskOrderCode = dto.TaskOrderCode;
                    inPut.Type = "已下发";
                    await baseService.UpdateTaskOrderState(inPut);
                    await baseService.CreateLog("上架", dto.BoxCode + "执行了上架任务");
                    InPut_BaseService7.BoxGridCode = "";
                    FullCode = "";
                    View_Box_MaterialDtos = null;
                    //CustomInPut4.rackcode = dto.WarehouseCode;
                    ////await customService.NotifyMes(CustomInPut4);
                    //CustomInPut4 = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LognetHelper.WriteLog("系统-CreateTaskOrder", ex);
            }
        }
        private async void DeleteMaterial()//删除物料
        {
            try
            {
                if (string.IsNullOrEmpty(LPN)) return;
                bool res = await baseService.Revoke_MaterialBase(LPN);
                if (res)
                {
                    GetList_View_Box_Material();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LognetHelper.WriteLog("系统-DeleteMaterial", ex);
            }

        }
        public void OnNavigatedTo(NavigationContext navigationContext)
        {

        }
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }
        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }

    }
}
